package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSit;
import com.nari.ncps.screen.entity.ne.NeProdoperPowerGs;
import com.nari.ncps.screen.entity.ne.NeProdoperPowerTotal;
import com.nari.ncps.screen.mapper.ne.NeProdoperPowerTotalMapper;
import com.nari.ncps.screen.service.ne.NeProdoperPowerTotalService;
import com.nari.ncps.screen.vo.ne.NePowerGenerationYoyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 新能源总发电量同比率统计表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperPowerTotalServiceImpl extends ServiceImpl<NeProdoperPowerTotalMapper, NeProdoperPowerTotal> implements NeProdoperPowerTotalService {

    @Autowired
    private NeProdoperPowerTotalMapper neProdoperPowerTotalMapper;

    @Override
    public List<NePowerGenerationYoyVO> getPowerGenerationYoyRate(Integer year) {

        // 获取当前年月
        YearMonth currentYearMonth = YearMonth.now();
        // 获取六个月前的年月（包含当前月，共7个月的范围）
        YearMonth sixMonthsAgoYearMonth = currentYearMonth.minusMonths(5); // 往前推5个月，加上当前月共6个月

        // 格式化为 yyyyMM
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String current = currentYearMonth.format(formatter);
        String sixMonthsAgo = sixMonthsAgoYearMonth.format(formatter);
        System.out.println("当前年月: " + current);      // 示例: 202412
        System.out.println("六个月前年月: " + sixMonthsAgo); // 示例: 202407


        LambdaQueryWrapper<NeProdoperPowerTotal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperPowerTotal::getOrgCode, "100360").eq(NeProdoperPowerTotal::getDateType, 1)
                .ge(NeProdoperPowerTotal::getStatisticTime, sixMonthsAgo).le(NeProdoperPowerTotal::getStatisticTime, current);
        // 从数据库查询指定年份的日发电数据（date_type = 2）
        List<NeProdoperPowerTotal> dataList = this.list(queryWrapper);
        // 如果数据库为空，直接返回空列表
        if (CollectionUtils.isEmpty(dataList)) {
            return new ArrayList<>();
        }

        // 将数据转换为VO对象
        return dataList.stream().map(data -> {
            NePowerGenerationYoyVO vo = new NePowerGenerationYoyVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());

            // 设置当年实际发电量
            BigDecimal currentYearGeneration = data.getActualGeneration() != null ? data.getActualGeneration() : BigDecimal.ZERO;
            vo.setCurrentYearGeneration(currentYearGeneration);

            // 将字符串转换为BigDecimal（去年同期发电量）
            BigDecimal lastYearGeneration = BigDecimal.ZERO;
            if (data.getLastYearActualGeneration() != null && !data.getLastYearActualGeneration().trim().isEmpty()) {
                try {
                    lastYearGeneration = new BigDecimal(data.getLastYearActualGeneration());
                } catch (NumberFormatException e) {
                    // 如果转换失败，使用默认值0
                    lastYearGeneration = BigDecimal.ZERO;
                }
            }
            vo.setLastYearGeneration(lastYearGeneration);

            // 计算同比率：((当年 - 去年) / 去年) * 100
            if (lastYearGeneration.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal yoyRate = currentYearGeneration.subtract(lastYearGeneration).divide(lastYearGeneration, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                vo.setYoyRate(yoyRate);
            } else {
                vo.setYoyRate(BigDecimal.ZERO);
            }

            return vo;
        }).collect(Collectors.toList());
    }
}
